import { useRef, useState } from 'react'
import { getEmotionColors } from '../utils/emotionColors'

const ShareCard = ({ poem, emotion, userInput, generatedImage, onClose }) => {
  const canvasRef = useRef(null)
  const [isGenerating, setIsGenerating] = useState(false)
  const [shareUrl, setShareUrl] = useState(null)

  // 生成分享卡片
  const generateShareCard = async () => {
    if (!poem || isGenerating) return

    setIsGenerating(true)
    
    try {
      const canvas = canvasRef.current
      const ctx = canvas.getContext('2d')
      
      // 设置画布尺寸 (适合社交媒体分享的比例)
      canvas.width = 800
      canvas.height = 1000
      
      // 清空画布
      ctx.clearRect(0, 0, canvas.width, canvas.height)
      
      // 获取情绪色彩
      const emotionColors = getEmotionColors(emotion)
      
      // 绘制背景
      await drawBackground(ctx, canvas, emotionColors, generatedImage)
      
      // 绘制内容
      drawContent(ctx, canvas, poem, emotion, userInput, emotionColors)
      
      // 转换为图片URL
      const dataUrl = canvas.toDataURL('image/jpeg', 0.9)
      setShareUrl(dataUrl)
      
    } catch (error) {
      console.error('生成分享卡片失败:', error)
    } finally {
      setIsGenerating(false)
    }
  }

  // 绘制背景
  const drawBackground = async (ctx, canvas, emotionColors, generatedImage) => {
    // 如果有AI生成的图片，使用它作为背景
    if (generatedImage?.success && generatedImage.imageUrl) {
      try {
        const img = new Image()
        img.crossOrigin = 'anonymous'

        await new Promise((resolve, reject) => {
          img.onload = resolve
          img.onerror = reject
          img.src = generatedImage.imageUrl
        })

        // 绘制背景图片，保持原始比例
        ctx.save()

        // 计算图片缩放比例，确保完全覆盖画布
        const imgAspect = img.width / img.height
        const canvasAspect = canvas.width / canvas.height

        let drawWidth, drawHeight, offsetX = 0, offsetY = 0

        if (imgAspect > canvasAspect) {
          // 图片更宽，以高度为准
          drawHeight = canvas.height
          drawWidth = drawHeight * imgAspect
          offsetX = (canvas.width - drawWidth) / 2
        } else {
          // 图片更高，以宽度为准
          drawWidth = canvas.width
          drawHeight = drawWidth / imgAspect
          offsetY = (canvas.height - drawHeight) / 2
        }

        // 绘制完整的背景图片
        ctx.globalAlpha = 0.85
        ctx.drawImage(img, offsetX, offsetY, drawWidth, drawHeight)
        ctx.restore()

        // 添加柔和的渐变遮罩，为文字创造更好的可读性
        const gradient = ctx.createRadialGradient(
          canvas.width / 2, canvas.height / 2, 0,
          canvas.width / 2, canvas.height / 2, Math.max(canvas.width, canvas.height) / 2
        )
        gradient.addColorStop(0, 'rgba(255, 255, 255, 0.1)')
        gradient.addColorStop(0.6, 'rgba(255, 255, 255, 0.3)')
        gradient.addColorStop(1, 'rgba(255, 255, 255, 0.6)')

        ctx.fillStyle = gradient
        ctx.fillRect(0, 0, canvas.width, canvas.height)

      } catch (error) {
        console.warn('背景图片加载失败，使用渐变背景')
        drawGradientBackground(ctx, canvas, emotionColors)
      }
    } else {
      // 使用情绪渐变背景
      drawGradientBackground(ctx, canvas, emotionColors)
    }
  }

  // 绘制渐变背景
  const drawGradientBackground = (ctx, canvas, emotionColors) => {
    const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height)
    gradient.addColorStop(0, emotionColors.primary + '20')
    gradient.addColorStop(0.5, emotionColors.secondary + '15')
    gradient.addColorStop(1, emotionColors.accent + '25')
    
    ctx.fillStyle = gradient
    ctx.fillRect(0, 0, canvas.width, canvas.height)
    
    // 添加纹理
    for (let i = 0; i < 50; i++) {
      ctx.save()
      ctx.globalAlpha = 0.1
      ctx.fillStyle = emotionColors.primary
      ctx.beginPath()
      ctx.arc(
        Math.random() * canvas.width,
        Math.random() * canvas.height,
        Math.random() * 30 + 10,
        0,
        Math.PI * 2
      )
      ctx.fill()
      ctx.restore()
    }
  }

  // 绘制内容
  const drawContent = (ctx, canvas, poem, emotion, userInput, emotionColors) => {
    const lines = poem.split('\n').filter(line => line.trim())

    // 分析图片内容，智能选择文字布局位置
    const layoutStrategy = analyzeImageLayout(canvas, lines.length)

    // 绘制情绪标签 - 使用半透明设计，更好融入背景
    drawEmotionTag(ctx, canvas, emotion, emotionColors, layoutStrategy)

    // 绘制用户输入引用 - 精简设计
    drawUserInput(ctx, canvas, userInput, layoutStrategy)

    // 绘制诗句 - 采用书法风格布局
    drawPoemText(ctx, canvas, lines, emotionColors, layoutStrategy)

    // 绘制底部信息
    drawFooterInfo(ctx, canvas, layoutStrategy)
  }

  // 分析图片布局，选择最佳文字位置
  const analyzeImageLayout = (canvas, lineCount) => {
    // 根据诗句行数和画布比例，智能选择布局策略
    const isVerticalPoem = lineCount <= 4
    const canvasRatio = canvas.width / canvas.height

    if (isVerticalPoem && canvasRatio < 1) {
      // 短诗 + 竖版画布：居中布局
      return {
        type: 'center',
        poemArea: {
          x: canvas.width * 0.1,
          y: canvas.height * 0.3,
          width: canvas.width * 0.8,
          height: canvas.height * 0.4
        },
        tagPosition: { x: canvas.width / 2, y: canvas.height * 0.15 },
        inputPosition: { x: canvas.width / 2, y: canvas.height * 0.22 },
        footerPosition: { x: canvas.width / 2, y: canvas.height * 0.85 }
      }
    } else {
      // 长诗或横版：分栏布局
      return {
        type: 'column',
        poemArea: {
          x: canvas.width * 0.15,
          y: canvas.height * 0.25,
          width: canvas.width * 0.7,
          height: canvas.height * 0.5
        },
        tagPosition: { x: canvas.width / 2, y: canvas.height * 0.12 },
        inputPosition: { x: canvas.width / 2, y: canvas.height * 0.18 },
        footerPosition: { x: canvas.width / 2, y: canvas.height * 0.88 }
      }
    }
  }

  // 绘制情绪标签
  const drawEmotionTag = (ctx, canvas, emotion, emotionColors, layout) => {
    ctx.save()

    // 创建柔和的背景
    const tagWidth = 140
    const tagHeight = 35
    const x = layout.tagPosition.x - tagWidth / 2
    const y = layout.tagPosition.y - tagHeight / 2

    // 绘制半透明背景
    ctx.fillStyle = 'rgba(0, 0, 0, 0.3)'
    ctx.roundRect(x, y, tagWidth, tagHeight, 18)
    ctx.fill()

    // 绘制边框光效
    ctx.strokeStyle = emotionColors.primary + '80'
    ctx.lineWidth = 2
    ctx.stroke()

    // 绘制文字
    ctx.fillStyle = 'white'
    ctx.font = 'bold 20px "KaiTi", "楷体", serif'
    ctx.textAlign = 'center'
    ctx.textBaseline = 'middle'
    ctx.fillText(emotion, layout.tagPosition.x, layout.tagPosition.y)

    ctx.restore()
  }

  // 绘制用户输入
  const drawUserInput = (ctx, canvas, userInput, layout) => {
    if (!userInput || userInput.trim().length === 0) return

    ctx.save()
    ctx.font = '16px "KaiTi", "楷体", serif'
    ctx.fillStyle = 'rgba(255, 255, 255, 0.9)'
    ctx.textAlign = 'center'
    ctx.textBaseline = 'middle'

    // 添加文字阴影增强可读性
    ctx.shadowColor = 'rgba(0, 0, 0, 0.5)'
    ctx.shadowBlur = 3
    ctx.shadowOffsetX = 1
    ctx.shadowOffsetY = 1

    const inputText = userInput.length > 25 ? userInput.substring(0, 25) + '...' : userInput
    ctx.fillText(`"${inputText}"`, layout.inputPosition.x, layout.inputPosition.y)

    ctx.restore()
  }

  // 绘制诗句文字 - 书法风格布局
  const drawPoemText = (ctx, canvas, lines, emotionColors, layout) => {
    ctx.save()

    const poemArea = layout.poemArea
    const maxLines = Math.min(lines.length, 8)

    // 根据布局类型选择不同的排版方式
    if (layout.type === 'center' && maxLines <= 4) {
      // 居中布局：适合短诗
      drawCenteredPoem(ctx, lines, poemArea, emotionColors)
    } else {
      // 分栏布局：适合长诗
      drawColumnPoem(ctx, lines, poemArea, emotionColors)
    }

    ctx.restore()
  }

  // 居中诗句布局
  const drawCenteredPoem = (ctx, lines, area, emotionColors) => {
    const lineHeight = Math.min(50, area.height / (lines.length + 1))
    const startY = area.y + lineHeight

    ctx.font = 'bold 32px "KaiTi", "楷体", serif'
    ctx.textAlign = 'center'
    ctx.textBaseline = 'middle'

    lines.forEach((line, index) => {
      if (index < 8) {
        const y = startY + index * lineHeight

        // 为每行文字添加柔和的背景
        const textWidth = ctx.measureText(line.trim()).width
        const padding = 20

        ctx.save()
        ctx.fillStyle = 'rgba(0, 0, 0, 0.2)'
        ctx.roundRect(
          area.x + area.width / 2 - textWidth / 2 - padding,
          y - lineHeight / 2 + 5,
          textWidth + padding * 2,
          lineHeight - 10,
          10
        )
        ctx.fill()
        ctx.restore()

        // 绘制文字
        ctx.fillStyle = 'white'
        ctx.shadowColor = 'rgba(0, 0, 0, 0.7)'
        ctx.shadowBlur = 4
        ctx.shadowOffsetX = 2
        ctx.shadowOffsetY = 2

        ctx.fillText(line.trim(), area.x + area.width / 2, y)
      }
    })
  }

  // 分栏诗句布局
  const drawColumnPoem = (ctx, lines, area, emotionColors) => {
    const maxLinesPerColumn = 4
    const columnCount = Math.ceil(lines.length / maxLinesPerColumn)
    const columnWidth = area.width / columnCount
    const lineHeight = Math.min(45, area.height / maxLinesPerColumn)

    ctx.font = 'bold 28px "KaiTi", "楷体", serif'
    ctx.textAlign = 'center'
    ctx.textBaseline = 'middle'

    lines.forEach((line, index) => {
      if (index < 8) {
        const columnIndex = Math.floor(index / maxLinesPerColumn)
        const lineInColumn = index % maxLinesPerColumn

        const x = area.x + columnIndex * columnWidth + columnWidth / 2
        const y = area.y + (lineInColumn + 1) * lineHeight

        // 为每行文字添加柔和的背景
        const textWidth = ctx.measureText(line.trim()).width
        const padding = 15

        ctx.save()
        ctx.fillStyle = 'rgba(0, 0, 0, 0.25)'
        ctx.roundRect(
          x - textWidth / 2 - padding,
          y - lineHeight / 2 + 5,
          textWidth + padding * 2,
          lineHeight - 10,
          8
        )
        ctx.fill()
        ctx.restore()

        // 绘制文字
        ctx.fillStyle = 'white'
        ctx.shadowColor = 'rgba(0, 0, 0, 0.8)'
        ctx.shadowBlur = 3
        ctx.shadowOffsetX = 1
        ctx.shadowOffsetY = 1

        ctx.fillText(line.trim(), x, y)
      }
    })
  }

  // 绘制底部信息
  const drawFooterInfo = (ctx, canvas, layout) => {
    ctx.save()

    // 创建底部信息背景
    const footerHeight = 40
    const footerY = layout.footerPosition.y - footerHeight / 2

    ctx.fillStyle = 'rgba(0, 0, 0, 0.4)'
    ctx.roundRect(60, footerY, canvas.width - 120, footerHeight, 20)
    ctx.fill()

    // 绘制应用信息
    ctx.font = '16px "KaiTi", "楷体", serif'
    ctx.fillStyle = 'rgba(255, 255, 255, 0.9)'
    ctx.textAlign = 'center'
    ctx.textBaseline = 'middle'

    const currentTime = new Date().toLocaleDateString('zh-CN')
    ctx.fillText(`心语国韵 · ${currentTime}`, layout.footerPosition.x, layout.footerPosition.y)

    ctx.restore()
  }

  // 下载分享卡片
  const downloadCard = () => {
    if (!shareUrl) return
    
    const link = document.createElement('a')
    link.href = shareUrl
    link.download = `诗词分享-${emotion}-${Date.now()}.jpg`
    link.click()
  }



  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-2xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
        {/* 头部 */}
        <div className="flex items-center justify-between p-6 border-b">
          <h2 className="text-2xl font-bold text-gray-800">📤 分享诗词</h2>
          <button
            onClick={onClose}
            className="text-gray-500 hover:text-gray-700 text-2xl"
          >
            ×
          </button>
        </div>
        
        {/* 内容区域 */}
        <div className="p-6 space-y-6">
          {/* 生成按钮 */}
          {!shareUrl && (
            <div className="text-center">
              <button
                onClick={generateShareCard}
                disabled={isGenerating}
                className="bg-gradient-to-r from-blue-500 to-purple-600 text-white px-8 py-3 rounded-full font-medium hover:shadow-lg transition-all disabled:opacity-50"
              >
                {isGenerating ? '🎨 生成中...' : '🎨 生成分享卡片'}
              </button>
            </div>
          )}
          
          {/* 预览区域 */}
          {shareUrl && (
            <div className="space-y-4">
              <div className="text-center">
                <img
                  src={shareUrl}
                  alt="分享卡片预览"
                  className="max-w-full h-auto rounded-lg shadow-lg mx-auto"
                  style={{ maxHeight: '400px' }}
                />
              </div>
              
              {/* 操作按钮 - 只保留下载功能 */}
              <div className="flex justify-center">
                <button
                  onClick={downloadCard}
                  className="bg-green-500 text-white px-6 py-3 rounded-lg hover:bg-green-600 transition-colors font-medium"
                >
                  💾 下载图片
                </button>
              </div>
              
              {/* 重新生成 */}
              <div className="text-center">
                <button
                  onClick={() => {
                    setShareUrl(null)
                    generateShareCard()
                  }}
                  className="text-gray-600 hover:text-gray-800 underline"
                >
                  🔄 重新生成
                </button>
              </div>
            </div>
          )}
        </div>
        
        {/* 隐藏的Canvas */}
        <canvas
          ref={canvasRef}
          style={{ display: 'none' }}
        />
      </div>
    </div>
  )
}

// Canvas roundRect polyfill
if (typeof CanvasRenderingContext2D !== 'undefined') {
  CanvasRenderingContext2D.prototype.roundRect = function(x, y, width, height, radius) {
    this.beginPath()
    this.moveTo(x + radius, y)
    this.lineTo(x + width - radius, y)
    this.quadraticCurveTo(x + width, y, x + width, y + radius)
    this.lineTo(x + width, y + height - radius)
    this.quadraticCurveTo(x + width, y + height, x + width - radius, y + height)
    this.lineTo(x + radius, y + height)
    this.quadraticCurveTo(x, y + height, x, y + height - radius)
    this.lineTo(x, y + radius)
    this.quadraticCurveTo(x, y, x + radius, y)
    this.closePath()
  }
}

export default ShareCard
